<template>
  <div class="content-area" >
    <el-container class="container-style">
      <el-container>
        <div style="width: 96%; margin: 0 auto; display: flex; flex-direction: column; align-items: center;">
          <div style="display: flex; align-items: center;">
              <h2>车位管理</h2>
          </div>

          <div style="background-color: white; padding: 20px; margin-top: 10px; width: 100%">
          <div class="table-header-container">
            <div class="search-container">
              <el-select v-model="searchOption" placeholder="请选择查询方式" class="search-select">
                <el-option label="按小区 ID 查询" value="communityId"></el-option>
                <el-option label="按车位状态查询" value="status"></el-option>
                <el-option label="按车位id查询" value="id"></el-option>
              </el-select>
              <el-input v-model="searchQuery"
                        :placeholder="
                  searchOption === 'status'? '已预定，已占用，空闲，维修中' :
                  '请输入查询关键词'
                "
                        class="search-input"></el-input>
              <el-button type="primary" @click="searchParking" class="search-button">查询</el-button>
            </div>
            <el-button type="primary" @click="addDialogFormVisible = true">增加记录</el-button>
          </div>


          <table v-if="parkingForm && parkingForm.data && parkingForm.data.records"
                 style="text-align: center; width: 100%; border-collapse: collapse;">
            <thead>
            <tr style="border: 1px solid #eee;">
              <th style="width: 50px;  border: 1px solid #eee;">车位id</th>
              <th style="width: 70px;  border: 1px solid #eee;">所属小区id</th>
              <th style="width: 100px;  border: 1px solid #eee;">车位位置</th>
              <th style="width: 50px;  border: 1px solid #eee;">车位状态</th>
              <th style="width: 100px;  border: 1px solid #eee;">创建时间</th>
              <th style="width: 100px;  border: 1px solid #eee;">更新时间</th>
              <th style="width: 50px;  border: 1px solid #eee;">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in parkingForm.data.records" :key="index" style="border: 1px solid #eee;">
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.id" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 70px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.communityId" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.location" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.status" :disabled="!item.isEdit" :class="{
        'normal-input-color':!item.isEdit,
        'edit-input-color': item.isEdit
      }" class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.createTime" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.updateTime" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <div class="button-group">
                  <template v-if="!item.isEdit">
                    <el-button type="success" @click="saveItem(item)">修改记录</el-button>
                    <el-button type="danger" @click="openDeleteDialog(item.id)">删除记录</el-button>
                  </template>
                  <template v-if="item.isEdit&&parkingForm && parkingForm.data && parkingForm.data.records.some(item => item.isEdit)">
                    <el-button type="success" @click="handleSaveEdit">保存修改</el-button>
                    <el-button type="default"  @click="handleCancelEdit" style="margin-left: 10px">取消修改</el-button>
                  </template>
                </div>
              </td>
            </tr>
            </tbody>
          </table>
          <div v-else-if="errorMessage">{{ errorMessage }}</div>
        </div>
          <div style="display: flex; justify-content: center; width: 100%;">
            <el-pagination
                class="footer"
                v-if="parkingForm && parkingForm.data"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[8, 10, 12]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="parkingForm.data.total"
            >
            </el-pagination>
          </div>
        </div>
      </el-container>
    </el-container>
    <el-dialog v-model="addDialogFormVisible" title="增加车位" width="500">
      <el-form :model="addForm">
        <el-form-item label="所属小区id" :label-width="formLabelWidth">
          <el-input v-model="addForm.communityId" placeholder="请输入小区id" />
        </el-form-item>
        <el-form-item label="车位位置" :label-width="formLabelWidth">
          <el-input v-model="addForm.location" placeholder="请输入车位位置" />
        </el-form-item>
        <el-form-item label="车位状态" :label-width="formLabelWidth">
          <el-select v-model="addForm.status" placeholder="请选择车位状态">
            <el-option v-for="option in parkingStatusOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleConfirm">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="deleteDialogFormVisible" title="删除车位" width="500">
      确定删除该车位信息？
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleDelete">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import * as echarts from "echarts";

export default {
  data() {
    return {
      errorMessage: '',
      currentPage: 1,
      pageSize: 12,
      addDialogFormVisible: false,
      addForm: {
        communityId: "",
        location: "",
        status: ""
      },
      showDialog: false,
      parkingForm: {
        id: "",
        communityId: "",
        location: "",
        status: "",
        createTime: "",
        updateTime: ""
      },
      parkingStatusOptions: [
        { label: '已预定', value: '已预定' },
        { label: '已占用', value: '已占用' },
        { label: '空闲', value: '空闲' },
        { label: '维修中', value: '维修中' }
      ],
      isEdit: false,
      saveEditId: null,
      originalInfo: null,
      searchQuery: '',
      deleteId: null,
      deleteDialogFormVisible: false,
      formLabelWidth: '120px',
      searchOption: "",
      newParking: {},
      unFreeCount: "",
      freeCount: "",
      repairingCount: "",
      orderedCount: ""
    };
  },
  setup() {
    const router = useRouter();
    return {
      router
    };
  },
  methods: {
    async fetchData() {
      try {
        const token = localStorage.getItem('token');
        let url = '/api/parking/page';
        let params = {
          current: this.currentPage,
          size: this.pageSize
        };
        if (this.searchOption =='communityId') {
          params.communityId = this.searchQuery;
        }else if(this.searchOption == 'status'){
          params.status = this.searchQuery;
        }
        const response = await axios.get(url, {
          headers: {
            Authorization: token
          },
          params: params
        });
        this.parkingForm = response.data;
        this.originalInfo = {...this.parkingForm} ;
        if (this.parkingForm && this.parkingForm.data && this.parkingForm.data.records) {
          this.parkingForm.data.records.forEach(item => {
            item.isEdit = false;
          });
        }
        console.log(response.data);
      } catch (error) {
        ElMessage.error('获取车位列表数据统计失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    handleConfirm() {
      this.confirmAdd();
    },
    async confirmAdd() {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.post(`/api/parking/${this.addForm.communityId}`, null, {
          headers: {
            Authorization: token
          },
          params:{
            communityId: this.addForm.communityId,
            location: this.addForm.location,
            status: this.addForm.status
          }
        });
        if (response.data.code === 200) {
          ElMessage.success('增加车位记录成功');
          this.addDialogFormVisible = false;
          this.fetchData();
        } else {
          ElMessage.error('增加车位记录失败,请输入正确信息');
        }
      } catch (error) {
        ElMessage.error('增加车位记录时出错：' + error.message);
      }
    },
    saveItem(item) {
      item.isEdit = true;
      this.saveEditId = item.id;
    },
    async handleSaveEdit() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          throw new Error('token不存在');
        }
        // 找到当前正在编辑的那一行数据
        const currentEditedItem = this.parkingForm.data.records.find(
            item => item.id === this.saveEditId
        );
        if (!currentEditedItem) {
          ElMessage.error('未找到当前编辑的车位记录');
          return;
        }
        const response = await axios.put(
            `/api/parking/${this.saveEditId}`,
            null,
            {
              headers: {
                Authorization: token
              },
              params:{
                id: currentEditedItem.id,
                communityId: currentEditedItem.communityId,
                location: currentEditedItem.location,
                status: currentEditedItem.status
              }
            }
        );
        if (response.data.code === 200) {
          this.fetchData();
          this.isEdit = false;
          ElMessage.success('车位信息修改成功');
        } else {
          ElMessage.error('车位信息修改失败，请输入正确信息');
        }
      } catch (error) {
        ElMessage.error('车位信息修改时出错：' + error.message);
      }
    },
    handleCancelEdit() {
      this.parkingForm = {...this.originalInfo };
      if (this.parkingForm && this.parkingForm.data && this.parkingForm.data.records) {
        this.parkingForm.data.records.forEach(item => {
          item.isEdit = false;
        });
      }
      this.isEdit = false;
    },
    async fetchStatusCounts() {
      this.showDialog = true;
      this.unFreeCount = await this.getRecordCountByStatus('已占用');
      this.orderedCount = await this.getRecordCountByStatus( '已预定');
      this.repairingCount = await this.getRecordCountByStatus( '维修中');
      this.freeCount = await this.getRecordCountByStatus('空闲');
      this.drawPieChart();
    },
    async getRecordCountByStatus(status) {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/api/parking/page', {
          headers: {
            Authorization: token
          },
          params: {
            current: this.currentPage,
            size: this.pageSize,
            status: status
          }
        });
        return response.data.data.total;
      } catch (error) {
        ElMessage.error('获取对应状态记录数量失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
        return 0;
      }
    },
    drawPieChart() {
      const chartDom = document.getElementById('barChart');
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '车位状态分布',
          subtext: `总记录数: ${this.unFreeCount + this.orderedCount + this.repairingCount + this.freeCount}`,
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['已占用', '已预定', '维修中', '空闲']
        },
        series: [
          {
            name: '状态分布',
            type: 'pie',
            radius: '50%',
            data: [
              { value: this.unFreeCount, name: '已占用' },
              { value: this.orderedCount, name: '已预定' },
              { value: this.repairingCount, name: '维修中' },
              { value: this.freeCount, name: '空闲' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      myChart.setOption(option);
    },
    async searchParking() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        if (this.searchOption === 'communityId') {
          const response = await axios.get('/api/parking/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.parkingForm = response.data;
            this.originalInfo = {...this.parkingForm };
          } else {
            ElMessage.error('查询车位信息失败');
          }
        }else if (this.searchOption === 'status') {
          const response = await axios.get('/api/parking/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              status: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.parkingForm = response.data;
            this.originalInfo = {...this.parkingForm };
          } else {
            ElMessage.error('查询车位信息失败');
          }
        }else if (this.searchOption === 'id') {
          const response = await axios.get(`/api/parking/${this.searchQuery}`, {
            headers: {
              Authorization: token
            }
          });
          console.log('parking',response)
          if (response.data.code === 200) {
            this.parkingForm.data.records = response.data.data;
            this.originalInfo = {...this.parkingForm };
          } else {
            ElMessage.error('查询车位信息失败，请输入正确信息');
          }
        }

      }catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    },
    openDeleteDialog(id){
      this.deleteId=id;
      this.deleteDialogFormVisible=true;
    },
    async handleDelete(){
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        const response = await axios.delete(`/api/parking/${this.deleteId}`, {
          headers: {
            Authorization: token
          }
        });
        if (response.data.code === 200) {
          ElMessage.success("删除成功");
          this.fetchData();
          this.deleteDialogFormVisible=false;
        } else {
          ElMessage.error('删除车位信息失败');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    }
  },
  mounted() {
    this.fetchData();
  }
};
</script>

<style scoped>

.footer {
  margin-top: 20px;
  text-align: center;
  padding: 10px;
  transition: margin-left 0.3s;
}


.container-style {
  height: 100%;
}

.content-area {
  background-color: #f2f5fa;
  padding: 20px;
  height: calc(100vh - 120px); /* 50(header) + 10(footer padding top) + 60(footer height & bottom margin) */
  overflow-y: auto; /* 启用滚动条 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.search-input {
  flex: 1;
  width: 250px;
  margin-right: 10px;
}

.search-button {
  min-width: 80px;
}

.table-header-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.disabled-style {
  cursor: default;
}


.form-label-width {
  width: 120px;
}
/* 未编辑时输入框颜色，这里假设为默认文本颜色，可按需调整 */
.normal-input-color {
  color: inherit;
}
/* 编辑时输入框颜色，这里假设为浅灰色，可按需调整 */
.edit-input-color {
  color: #ccc;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.search-input {
  flex: 1;
  width: 400px;
  margin-right: 10px;
}

.search-select {
  flex: 1;
  width: 30px;
}

</style>